<script setup lang="ts" name="SelectHold">

import { onMounted, ref, watch } from "vue";
import type { HoldItem } from "@/utils/interface";
const input = defineProps(["holdList", "selectedHold", "arrangeId"]);
const emit = defineEmits(["isOpen", "selectHold"]);

const loading = ref(false);
const resData = ref({} as HoldItem);
const holdItemList = ref([] as Array<HoldItem>);

onMounted(() => {
  init();
});

watch(
  () => input.arrangeId,
  () => {
    holdItemList.value = [];
    init();
  },
  { immediate: true }
);

function init() {
  holdItemList.value = input.holdList;
  if (
    holdItemList.value &&
    holdItemList.value.length > 0 &&
    input.selectedHold
  ) {
    holdItemList.value.forEach(item => {
      item.isSelected = item.hold === input.selectedHold;
    });
  }
}

function selectItem(data: HoldItem) {
  holdItemList.value.forEach(item => {
    item.isSelected = item.hold === data.hold;
  });
  resData.value = data;
}

function returnRes() {
  emit("selectHold", resData.value);
  showPop(false);
}

function showPop(show: boolean) {
  emit("isOpen", show);
}
</script>

<template>
  <div class="flex-col h-[auto] p-[20px] w-full" style="background: #f6f6f6">
    <div class="flex h-[30px] justify-between">
      <div
        class="flex justify-center items-center h-full text-center text-base"
      >
        选择舱口
      </div>
      <div
        class="flex h-full justify-center items-center text-center text-base"
      >
        <div class="text-sky-500" @click="returnRes">确定</div>
      </div>
    </div>
    <div class="flex py-[12px] w-full h-auto flex-wrap gap-2">
      <van-loading
        class="flex w-full justify-center h-[80px] items-center"
        v-if="loading"
        color="#1989fa"
      />
      <div
        :class="{ selected: item.isSelected, unselected: !item.isSelected }"
        class="flex border-2 border-white py-[5px] px-[10px] w-auto text-sm rounded"
        v-for="item in holdItemList"
        :key="item.hold"
        @click="selectItem(item)"
      >
        {{ item.holdName }}
      </div>
    </div>
  </div>
</template>

<style scoped>
.unselected {
  background: #ffffff;
  color: #000000;
}
.selected {
  background: #3869fc;
  color: #ffffff;
}
</style>
